<template>
  <div class="scoring-content-report-wrapper">
    <!-- 功能面板区域 -->
    <div v-if="imgPreview">
      <div v-if="ratingContent"
        class="content-tools-hover-wrapper"
        @mouseover="toolsMouseover"
        @mouseleave="toolsMouseleave">
        <div class="content-tools-main-wrapper"
          v-show="htmlToolsVisible">
          <div class="tools-left"></div>
          <div class="tools-center"></div>
          <div class="tools-right">
            <div class="tool-item-catalog"
              @click="download()">
              <span title="下载">
                <el-icon>
                  <Download />
                </el-icon>
              </span>
            </div>
          </div>
        </div>
      </div>
      <div class="pdf-content">
        <div class="imgPreview"
          style="padding: 10px 10px 0 10px;width: 100%;height: 100%;">
          <el-scrollbar height="100%"
            always
            style="background-color: #ffffff">
            <img :src="scroingImg"
              class="scroing-img" />
          </el-scrollbar>
        </div>
      </div>
    </div>
    <div class="zipPreview"
      v-if="zipPreview">
      <el-empty description="暂不支持该格式文件预览，请在【底稿文件】中查看！" />
    </div>
    <div v-if="pdfPreview">
      <!-- 功能面板区域 -->
      <div v-if="ratingContent"
        class="content-tools-hover-wrapper"
        @mouseover="toolsMouseover"
        @mouseleave="toolsMouseleave">
        <div class="content-tools-main-wrapper"
          v-show="htmlToolsVisible">
          <div class="tools-left">
            <div class="tool-item-catalog"
              style="width: 100px;">
              <span>共 {{ state.pageNum }} 页</span>
            </div>
          </div>
          <div class="tools-center">
            <div style="background: transparent; width: 150px;display: flex;align-items: center;justify-content: center">
              <Minus class="scale-btn"
                style="margin-right: 10px;cursor: pointer;"
                @click="onScaleEvents('sub')" />
              <span style="padding: 5px 10px;background: #585858; border-radius: 4px; ">{{
                            scaleOptions[scaleIndex].label
                            }}</span>
              <Plus class="scale-btn"
                style="margin-left: 10px;cursor: pointer;"
                @click="onScaleEvents('add')" />
            </div>
          </div>
          <div class="tools-right">
            <div class="tool-item-catalog"
              @click="reloadOpen">
              <span title="重新打开">
                <el-icon>
                  <FolderOpened />
                </el-icon>
              </span>
            </div>
            <div class="tool-item-catalog"
              @click="download()">
              <span title="下载">
                <el-icon>
                  <Download />
                </el-icon>
              </span>
            </div>
          </div>
        </div>
      </div>
      <!-- Pdf显示区域 -->
      <div class="pdf-content"
        :style="{'--scale-factor':scaleOptions[scaleIndex].value}"
        v-loading="loading">
        <div style="padding: 10px 10px 0 10px;width: 100%;height: 100%;">
          <el-scrollbar height="100%"
            always
            @scroll="scroll"
            style="background-color: #ffffff">
            <div :id="`page_${page}`"
              v-for="page in state.pageNum"
              :key="page"
              class="pdf-item">
              <VuePdf v-if="isReload"
                :src="pdfFile"
                :page="page"
                :scale="scaleOptions[scaleIndex].value"
                :enable-text-selection="false" />
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Download,Plus,FolderOpened,Minus } from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'
import { VuePdf, createLoadingTask } from 'vue3-pdfjs/esm';
import { nextTick, onMounted, reactive, ref, unref, watch } from "vue";
import * as pdfjsLib from "pdfjs-dist";
import { useRouter } from "vue-router";

import { previewFile, fileType, openNewWindow, dowloadFile } from '@/utils/file-utils.js';

import { useFileApi } from '@/api/index'
const { downloadFileData, previewFileData } = useFileApi();
const router = useRouter();
// 财务评价报告pdf预览
const props = defineProps({
  attachmentType: {
    type: Number,
    default: 1
  },
  fileId: {
    type: [String, Number],
    default: " "
  },
  position: {
    type: [String, Number],
    default: " "
  },
  title: {
    type: String,
    default: " "
  },
})

let loading = ref(true)
const ratingContent = ref(true)
let pdfCtx = null
const activePage = ref(1)

const basicSize = reactive({
  scale: 1.33333
})
const scaleIndex = ref(2)

const scaleOptions = [
  {
    value: basicSize.scale * 0.25,
    label: '25%',
  },
  {
    value: basicSize.scale * 0.5,
    label: '50%',
  }, {
    value: basicSize.scale * 1.0,
    label: '100%',
  }, {
    value: basicSize.scale * 1.1,
    label: '125%',
  }, {
    value: basicSize.scale * 1.5,
    label: '150%',
  }, {
    value: basicSize.scale * 2,
    label: '200%',
  }
]
const isReload = ref(true)
const state = reactive({
  pageNum: 0,
  scale: 1.33333
})
const fileSrcLoaded = ref(true)
watch(() => [props.fileId, props.position], ([v1, v2]) => {
  getPdfSrc();
})

let imgPreview = ref(false)
let zipPreview = ref(false)
let pdfPreview = ref(false)
let scroingImg = ref(null)
let reviewFileType = ref(null)
//获取pdf
let pdfFile = ref(null)
let reviewpdfFile = ref(null)
const getPdfSrc = () => {
  previewFileData(props.fileId).then(result => {
    reviewFileType.value = result.type
    const blob = new Blob([result], { type: result.type });
    if (result.type == 'application/pdf') {
      reviewpdfFile.value = result
      pdfFile.value = window.URL.createObjectURL(blob)
      open(pdfFile.value)
      pdfPreview.value = true
    } if (result.type == 'image/png' || result.type == 'image/jpg' || result.type == 'image/jpeg' || result.type == 'image/gif') {
      scroingImg.value = window.URL.createObjectURL(blob)
      imgPreview.value = true
    } else {
      zipPreview.value = true
    }
  });

}

//打开PDF文件
const open = (src) => {
  createLoadingTask(src).promise.then(pdf => {
    //赋值
    pdfCtx = pdf
    //获取总页面数
    state.pageNum = pdf.numPages
    loading.value = false
  })
}

const toPage = (pageNumber) => {
  // 滚动到目标页面
  const pageElement = document.getElementById(`page_${pageNumber}`);
  if (pageElement) {
    pageElement.scrollIntoView({ behavior: "smooth" });
  }
}
const onScaleEvents = (type) => {
  if (type === 'add') {
    if (scaleIndex.value === scaleOptions.length - 1) {
      return
    }
    scaleIndex.value = scaleIndex.value + 1
  } else if (type === 'sub') {
    if (scaleIndex.value === 0) {
      return
    }
    scaleIndex.value = scaleIndex.value - 1
  }
  isReload.value = false
  setTimeout(() => {
    isReload.value = true
  }, 100)
}

async function download() {
  if (reviewFileType.value == "application/pdf") {
    let url = "";
    let file = unref(pdfFile.value)
    if (typeof file === "string") {
      url = file
    } else {
      url = URL.createObjectURL(file)
    }
    let filename = pdfjsLib.getFilenameFromUrl(url)
    const data = await pdfCtx.getData();

    const blob = new Blob([data], {
      type: "application/pdf"
    });

    const blobUrl = URL.createObjectURL(blob);

    const a = document.createElement("a");
    if (!a.click) {
      throw new Error('DownloadManager: "a.click()" is not supported.');
    }
    a.href = blobUrl;
    a.target = "_parent";
    if ("download" in a) {
      a.download = filename;
    }
    (document.body || document.documentElement).append(a);
    a.click();
    a.remove();
  } else {
    ElMessage({ message: '文件正在下载，请稍后！', type: "info" });
    const loading = ElLoading.service({
      lock: true,
      text: '加载中',
    })
    const result = await downloadFileData(props.fileId)
    const code = result?.code
    const msg = result?.message
    if (code) {
      loading.close()
      ElMessage({ message: msg ?? '业务失败！', type: "error" });
    } else {
      if (result) {
        let filename = new Date().getTime();
        dowloadFile(result, filename, reviewFileType.value)
        loading.close()
      } else {
        ElMessage({ message: '没有任何数据！', type: "warning" });
        loading.close()
      }
    }
  }
}

/**
 * 重新打开
 */
const reloadOpen = async () => {
  const viewLoading = ElLoading.service({
    lock: true,
    text: '生成中...',
  })
  if (reviewpdfFile.value) {
    let url = null
    viewLoading.close()
    url = previewFile(reviewpdfFile.value, fileType.pdf)
    openNewWindow(url, props.title)
  } else {
    viewLoading.close()
    ElMessage({ message: '没有任何数据！', type: "warning" });
  }
}


/** 工具栏鼠标移入 */
// 目录是否出现
let buildCatalogVisible = ref(false);
let htmlToolsVisible = ref(false);
const toolsMouseover = () => {
  if (!buildCatalogVisible.value) {
    htmlToolsVisible.value = true
  }
}
/** 工具栏鼠标移出 */
const toolsMouseleave = () => {
  if (!buildCatalogVisible.value) {
    htmlToolsVisible.value = false
  }
}

const scroll = ({ scrollTop }) => {
  //计算单页面高度
  let pdfFirst = document.querySelectorAll(".pdf-item")[0];
  if (pdfFirst) {
    //计算当前activePage
    activePage.value = Math.trunc(scrollTop / pdfFirst.clientHeight) + 1
  }
}

onMounted(() => {
  nextTick(() => {
    if (props.fileId) {
      getPdfSrc();
    }
  })

})

defineExpose({
  toPage,
  download,
  reloadOpen
})
</script>

<style lang="scss" scoped>
@import './scss/expert-scoring-scoped.scss';

.scale-btn {
	width: 20px;
	height: 20px;
}

.scoring-content-report-wrapper,
.pdfPreview,
.imgPreview,
.zipPreview {
	border-radius: 4px;
	height: 100%;
}
.pdfPreview,
.imgPreview,
.zipPreview {
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}
.imgPreview {
	overflow-y: scroll;
}
.scroing-img {
	width: 100%;
	height: auto;
}
.pdf,
.img {
	display: flex;
	height: 100%;
	position: relative;
	background-color: #d4d4d7;
	flex-direction: column;

	&-toolbar {
		width: 100%;
		height: 40px;
		background-color: #f9f9fa;
		padding-left: 10px;
		display: flex;
		align-items: center;
		box-sizing: border-box;
		border: 1px solid #cecccc;
		position: relative;
	}

	&-content {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: #535659;
	}

	&-item {
		margin: 10px auto;
		width: calc(var(--scale-factor) * 612px);
		/*height: calc(var(--scale-factor) * 792px);*/
	}
}
</style>
